﻿using System.Collections.Generic;

namespace SMARTMobile.WinPhone
{
    /// <summary>
    /// Reresents the current state of a phone-page that can be stored and restored in tombstone mode.
    /// </summary>
    public class PhonePageState
    {
        private readonly IDictionary<string, object> _state;

        #region Constructors

        public PhonePageState()
        {
            this._state = new Dictionary<string, object>();
        }

        public PhonePageState(IDictionary<string, object> state)
        {
            this._state = state;
        }

        #endregion

        /// <summary>
        /// Restores page's last state.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The page name (usually).</param>
        /// <returns>Page's last state.</returns>
        public T Read<T>(string key)
        {
            if (this._state.ContainsKey(key))
            {
                T result = (T)_state[key];
                this._state.Remove(key);

                return result;
            }

            return default(T);
        }

        public void Write(string key, object value)
        {
            if (this._state.ContainsKey(key))
            {
                System.Diagnostics.Debug.WriteLine("CLPageState already contains key={0}. Overwriting...", key);
                this._state[key] = value;
            }
            else
            {
                this._state.Add(key, value);
            }
        }
    }
}
